<!-- ArticleDetails.vue -->
<!--文章详情组件-->
<template>
  <div class="article-details">
    <p style="text-align:center;padding-top:5px;font-size: 25px">{{ article.title }}</p>
    <div v-html="renderedArticle" class="article-html"></div>
  </div>
</template>

<script>
import service from "@/utils/service";

export default {
  props: ["articleId"], // 接收动态路由参数作为组件属性，文章的id
  data() {
    return {
      article: "", //存储文章详细信息

    };
  },
  //计算属性
  computed: {
    renderedArticle() {
      // 将文章内容解析成 DOM 对象
      const parser = new DOMParser();
      const doc = parser.parseFromString(this.article.content, "text/html");

      // 查找所有图片标签并添加样式
      const images = doc.querySelectorAll("img");
      images.forEach((img) => {
        img.style.maxWidth = "100%"; // 设置最大宽度
        img.style.height = "auto"; // 高度自适应以保持比例
        img.style.objectFit = "cover"; // 保持比例并填充容器
      });

      // 将处理后的 HTML 字符串返回
      return doc.body.innerHTML;
    },
  },

  created() {
    // 根据传递的 articleId 获取对应的文章信息
    const articleId = this.articleId;
    this.article = this.fetchArticleDetails(articleId);
    this.addArticleReadCount(articleId);
  },

  methods: {
    async fetchArticleDetails(articleId) {
      try {
        const response = await service.get(
          `/articles/getbyId?article_id=${articleId}`
        );

        const responseData = response.data;

        if (responseData.code === 20041) {
          this.article = responseData.data;
          console.log('返回的文章对象为',responseData.data);

        }
      } catch (error) {
        console.error(error);
        // 在这里处理错误
      }
    },
    //增加文章阅读数接口
    async addArticleReadCount(article_id) {
      try {
        const apiUrl = "/articles/increaseReadcount";
        const response = await service.put(apiUrl, {
          article_id: article_id,
        });

        if (response.data.code === 20031) {
          console.log(response.data.data);
        }
      } catch {
        console.log('增加文章阅读数出错');
      }
    },
  },
};
</script>

<style scoped>
h1 {
  text-align: center;
}

.article-details {
  width: 1120px;
  /*border: 1px solid #ccc;*/
}

.article-html {
  margin: 10px 0px;
  max-width: 100%;
  max-height: 100%;
  overflow: auto;

}
</style>

